package com.rtsapp.server.platform.pp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.platform.IPlatformLoginService;
import com.rtsapp.server.utils.StringUtils;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import com.rtsapp.server.logger.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;

/**
 * PP助手的登陆SDK
 */
public class PPLoginService implements IPlatformLoginService {

    private static final Logger LOGGER = com.rtsapp.server.logger.LoggerFactory.getLogger( PPLoginService.class );

    //    http://passport_i.25pp.com:8080/account?tunnel-command=2852126760
    private static final String url = AppConfig.getInstance().getPPUrl();
    //    7325
    private static final String appId = AppConfig.getInstance().getPPAppId();
    //    60d9dbc9b04644281dc1a100b35481d3
    private static final String appKey = AppConfig.getInstance().getPPAppKey();

    private static final int PP_CODE_OK = 1;
//    private static final int PP_CODE_REQUEST_PARAM_ERROR = 10;
//    private static final int PP_CODE_REQUEST_TIMEOUT = 11;
//    private static final int PP_CODE_SERVER_ERROR = 1;



    @Override
    public String validateLoginToken(  String token, String uid ){

        try {

            String json = checkSession(token, appId, appKey);

            if( ! StringUtils.isEmpty( json ) ){

                JSONObject jsonObject =  JSON.parseObject(json);
                JSONObject stateObject =  jsonObject.getJSONObject("state");

                int  code =  stateObject.getIntValue( "code" );
                if( code == PP_CODE_OK ) {

                    JSONObject dataObject = jsonObject.getJSONObject( "data" );
                    String accountId=  dataObject.getString("accountId");

                    LOGGER.debug("pp助手:有效用户:userid=" + accountId);
                    return "pp_" + accountId;
                }

            }
        } catch (IOException e) {
            LOGGER.error( "pp助手用户验证调用异常", e );
            return null;
        }

        LOGGER.debug("pp助手:用户验证失败" );
        return null;
    }


    /**
     * 验证session
     * @param session
     * @param appId
     * @param appKey
     * @return
     * @throws IOException
     */
    public static String checkSession(String session, String appId, String appKey) throws IOException
    {
        if (null == session || null == appId || null == appKey)
        {
            return null;
        }
        String sign = md5("sid=" + session + appKey);
        JSONObject params = new JSONObject();
        params.put("id", Long.valueOf(System.nanoTime()));
        params.put("service", "account.verifySession");
        params.put("encrypt", "md5");
        params.put("sign", sign);
        JSONObject param1 = new JSONObject();
        param1.put("sid", session);
        params.put("data", param1);
        JSONObject param2 = new JSONObject();
        param2.put("gameId", appId);
        params.put("game", param2);
        return httpPostJson(url, params.toString());
    }

    /**
     * http post json string
     * @param url
     * @param content
     * @return
     * @throws IOException
     */
    public static String httpPostJson(String url, String content) throws IOException
    {
        if (null == url || url.isEmpty() || null == content || content.isEmpty())
        {
            return "";
        }
        // 请求地址
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        // 设置超时时间为3s
        RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setAuthenticationEnabled(false).build();
        httpPost.setConfig(config);
        // 设置参数
        StringEntity se = new StringEntity(content);
        se.setContentType("text/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(se);
        // 准备环境
        try (CloseableHttpClient http = HttpClients.createDefault(); CloseableHttpResponse response = http.execute(httpPost);)
        {
            // 返回内容
            HttpEntity entity = response.getEntity();
            // 主体数据
            InputStream in = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            // 读取
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            return sb.toString();
        }
    }

    /**
     * MD5加密
     * @param s
     *        被加密的字符串
     * @return 加密后的字符串
     */
    public static String md5(String s)
    {
        if (s == null) s = "";
        try
        {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(s.getBytes("UTF-8"));
            return new String(Hex.encodeHex(mdTemp.digest()));
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
    
}
